<template>
  <div class="acount-exchange person-bg">
    <div class="text-14 text-bolder color_42 rate-box mb-20 quoteinpbg">
      {{ $t("stock.referenceRate") }}:1
      {{ state.defaultFiat?.virtual_currency_name }} =
      {{ state.defaultFiat?.exchange_rate }}
      {{ state.defaultFiat?.currency_name }}
    </div>
    <div class="mg-bt-30">
      <div class=" color_98 mb-6 text-left text-14">
        选择账户
      </div>
      <el-select
        v-model="state.virtualCoin"
        :placeholder="$t('exchange.currencyTip')"
        @change="(item) => changePrice(item, 1)"
      >
        <el-option
          v-for="item in state.virtualArr"
          :key="item.virtual_currency_id"
          :label="item.virtual_currency_name"
          :value="item.virtual_currency_id"
        />
      </el-select>
    </div>
    <div class="mb-6 text-14 flex js-sp align-center">
      <div class=" color_98 ">
        {{ state.exchange_type === true ? "支付" : "获得" }}
      </div>
      <div class="color_42  ">
        {{ $t("deal.available") }} {{ state.balance }}
        {{
          state.exchange_type === true
            ? state.defaultFiat?.virtual_currency_name
            : state.defaultFiat?.currency_name
        }}
      </div>
    </div>
    <div class="mb-32 flex js-sp align-center" v-if="state.exchange_type">
      <div class="flex-grow-1 top">
        <el-input
          v-model="state.virtual_currency_amount"
          @input="changeVirtualCurrency"
          :placeholder="$t('stock.digitalTip')"
        >
          <template #suffix>
            <span class="text-link text-14 point person-bg" @click="allin">{{
              $t("financial.all")
            }}</span>
          </template>
        </el-input>
      </div>
      <div class="w-150 flex-shrink-0 ml-16">
        <el-select
          v-model="state.virtualCoin"
          :placeholder="$t('exchange.currencyTip')"
          @change="(item) => changePrice(item, 1)"
        >
          <el-option
            v-for="item in state.virtualArr"
            :key="item.virtual_currency_id"
            :label="item.virtual_currency_name"
            :value="item.virtual_currency_id"
          />
        </el-select>
      </div>
    </div>
    <div class="mb-32 flex js-sp align-center" v-else>
      <div class="flex-grow-1">
        <el-input
          v-model="state.currency_amount"
          :placeholder="$t('stock.fiatTip')"
          @input="changeCurrency"
        >
          <template #suffix>
            <span class="text-link text-14 point" @click="allin">{{
              $t("financial.all")
            }}</span>
          </template>
        </el-input>
      </div>
      <div class="w-150 flex-shrink-0 ml-16">
        <el-select
          v-model="state.currency_name"
          :placeholder="$t('legal.chooseCurrency')"
          @change="(item) => changePrice(item, 2)"
        >
          <el-option
            v-for="(item, index) in state.currency"
            :key="index"
            :label="item.currency_name"
            :value="item.currency_name"
          />
        </el-select>
      </div>
    </div>
    <div class="mb-20">
      <svg-icon
        data-_icon-name="ic_fiat_exchange"
        class="text-40"
        @click="changeType"
      ></svg-icon>
    </div>
    <div class="mb-6 text-14 flex js-st align-center">
      <div class=" color_98 ">
        {{ state.exchange_type === true ? "获得" : "支付" }}
      </div>
    </div>
    <div class="mb-30 flex js-sp align-center" v-if="state.exchange_type">
      <div class="flex-grow-1">
        <el-input
          v-model="state.currency_amount"
          :placeholder="$t('stock.fiatTip')"
          @input="changeCurrency"
        >
        </el-input>
      </div>
      <div class="w-150 flex-shrink-0 ml-16">
        <el-select
          v-model="state.currency_name"
          :placeholder="$t('legal.chooseCurrency')"
          @change="(item) => changePrice(item, 2)"
        >
          <el-option
            v-for="(item, index) in state.currency"
            :key="index"
            :label="item.currency_name"
            :value="item.currency_name"
          />
        </el-select>
      </div>
    </div>
    <div class="mb-30 flex js-sp align-center" v-else>
      <div class="flex-grow-1">
        <el-input
          v-model="state.virtual_currency_amount"
          @input="changeVirtualCurrency"
          :placeholder="$t('stock.digitalTip')"
        >
        </el-input>
      </div>
      <div class="w-150 flex-shrink-0 ml-16">
        <el-select
          v-model="state.virtualCoin"
          :placeholder="$t('exchange.currencyTip')"
          @change="(item) => changePrice(item, 1)"
        >
          <el-option
            v-for="item in state.virtualArr"
            :key="item.virtual_currency_id"
            :label="item.virtual_currency_name"
            :value="item.virtual_currency_id"
          />
        </el-select>
      </div>
    </div>
    <div
      class="btn radius login-btn text-16 share-color point"
      v-loading="state.loading"
      @click="submitForm"
    >
      {{ $t("stock.quickExchange") }}
    </div>
  </div>
</template>

<script>
import { onMounted, reactive, computed, watch } from "vue";
import {
  stockCurrencyFindAll,
  stockCurrencyExchange,
  stockCurrencyBalance,
} from "@/api/stock";
import { transferInfo } from "@/api/assets";
import { toBeNumber, decimalDigitsInputFilter } from "@/utils/common";
import { rideFix, exceptFix } from "@/utils/precisionMath";
import { ElMessage } from "element-plus";
import { useI18n } from "vue-i18n";
import { useStore } from "vuex";
export default {
  props: { type: Number, virtual_currency_id: Number, id: Number },
  emits: ["close", "getbalance"],
  setup(props, { emit }) {
    const { t } = useI18n();
    const state = reactive({
      virtual_currency_amount: "", //法币，虚拟法币数量
      currency_amount: "", //国家法币数量
      virtualCoin: "", //法币/虚拟法币id
      currency_name: "", //国家法币名字
      exchange_type: true, //划转类型（true-数字货币转国家法币，false-国家法币转数字货币
      changeParam: {},
      param: { transfer_type: props.type === 0 ? 2 : props.type },
      currency: [],
      balance: "-", //账户余额
      loading: false,
      virtualArr: [],
      defaultFiat: {},
    });
    const $store = useStore();
    const systemInfo = computed(() => {
      return $store.state.user.systemInfo;
    });
    /**
     * methods
     */
    onMounted(() => {
      console.log("props", props.type, typeof props.type);
      getcurrency();
    });
    watch(
      () => state.param.transfer_type,
      (newValue) => {
        if (newValue) {
          getcurrency();
        }
      }
    );
    // 选择框变换币种
    const changePrice = (item, type) => {
      if (type === 1) {
        let val = state.currency.filter((ele) => {
          return ele.virtual_currency_name === state.currency_name;
        });
        console.log("item", val);
        // state.changeParam.virtual_currency_name = state.virtualCoin;
        // state.changeParam.currency_name = null;
        // getcurrency();
        if (val.length > 0) {
          state.defaultFiat = val[0];
          state.currency_name = val[0].currency_name;
          if (state.virtual_currency_amount) {
            state.currency_amount = rideFix(
              state.virtual_currency_amount,
              val[0].exchange_rate
            );
          } else if (state.currency_amount) {
            state.virtual_currency_amount = exceptFix(
              state.currency_amount,
              val[0].exchange_rate
            );
          }
        }
      } else if (type === 2) {
        let val = state.currency.filter((ele) => {
          return ele.currency_name === item;
        });
        console.log("item", val);
        updateVirtualArr(state.currency_name);
        // state.changeParam.currency_name = state.currency_name;
        // state.changeParam.virtual_currency_name = null;
        // getcurrency();
        if (val.length > 0) {
          state.defaultFiat = val[0];
          state.virtualCoin = val[0].virtual_currency_id;
          if (state.currency_amount) {
            state.virtual_currency_amount = exceptFix(
              state.currency_amount,
              val[0].exchange_rate
            );
          } else if (state.virtual_currency_amount) {
            state.currency_amount = rideFix(
              state.virtual_currency_amount,
              val[0].exchange_rate
            );
          }
        }
      }
    };
    // 改变划转方向
    const changeType = () => {
      state.exchange_type = !state.exchange_type;
      getBalance();
    };
    // 初始化数组
    const init = (list) => {
      const tempArr = JSON.parse(JSON.stringify(list));
      // 数组去重
      let obj = {};
      state.currency = tempArr.reduce((cur, next) => {
        obj[next.currency_name]
          ? ""
          : (obj[next.currency_name] = true && cur.push(next));
        return cur;
      }, []);
      updateVirtualArr(state.defaultFiat?.currency_name);
    };
    const updateVirtualArr = (currency_name) => {
      const tempArr = JSON.parse(JSON.stringify(state.currency));
      let virtualArrTemp = tempArr.filter(
        (item) => item.currency_name === currency_name
      );
      let obj = {};
      state.virtualArr = virtualArrTemp.reduce((cur, next) => {
        obj[next.virtual_currency_name]
          ? ""
          : (obj[next.virtual_currency_name] = true && cur.push(next));
        return cur;
      }, []);
    };
    // 获取国家法币币种
    const getcurrency = () => {
      let param = state.changeParam;
      stockCurrencyFindAll(param).then((res) => {
        let list = [...res.data];
        state.currency = list;
        if (list.length > 0) {
          let defaultAry = [];
          if (props.virtual_currency_id) {
            defaultAry = list.filter((ele) => {
              if (props.id) {
                return (
                  ele.virtual_currency_id === props.virtual_currency_id &&
                  ele.id === props.id
                );
              } else {
                return ele.virtual_currency_id === props.virtual_currency_id;
              }
            });
          } else {
            defaultAry = list.filter((ele) => {
              return ele.is_default === true;
            });
          }
          state.virtualCoin = defaultAry[0].virtual_currency_name;
          if (defaultAry.length > 0) {
            state.defaultFiat = defaultAry[0];
            state.currency_name = state.defaultFiat?.currency_name;
          } else {
            state.defaultFiat = list[0];
            state.currency_name = state.defaultFiat?.currency_name;
          }
          init(list);
          getBalance();
        }
      });
    };
    // 获取股票币种余额信息
    const getBalance = () => {
      if (state.exchange_type) {
        //虚拟
        if (!state.virtualCoin) {
          // 没选择币种
          return;
        }
        const param = {
          transfer_type: 1,
          currency_name: state.virtualCoin,
        };
        transferInfo(param).then((res) => {
          state.balance = res.data.balance;
        });
      } else {
        if (!state.currency_name) {
          // 没选择币种
          return;
        }
        let val = state.currency.filter((ele) => {
          return ele.currency_name === state.currency_name;
        });
        stockCurrencyBalance(val[0].id).then((res) => {
          state.balance = res.data.legal_balance;
        });
      }
    };
    // 划转数量变化
    const changeVirtualCurrency = (val) => {
      if (val) {
        let tempV = toBeNumber(val);
        state.virtual_currency_amount = decimalDigitsInputFilter(
          tempV,
          state.defaultFiat?.virtual_currency_accuracy
        );
        let num = rideFix(
          state.virtual_currency_amount,
          state.defaultFiat?.exchange_rate
        );
        state.currency_amount = decimalDigitsInputFilter(
          num,
          state.defaultFiat?.currency_accuracy
        );
      } else {
        state.currency_amount = "";
      }
    };
    const changeCurrency = (val) => {
      if (val) {
        let tempV = toBeNumber(val);
        state.currency_amount = decimalDigitsInputFilter(
          tempV,
          state.defaultFiat?.currency_accuracy
        );
        let num = exceptFix(
          state.currency_amount,
          state.defaultFiat?.exchange_rate
        );
        state.virtual_currency_amount = decimalDigitsInputFilter(
          num,
          state.defaultFiat?.virtual_currency_accuracy
        );
      } else {
        state.virtual_currency_amount = "";
      }
    };
    // 全部划转
    const allin = () => {
      if (state.exchange_type) {
        state.virtual_currency_amount = state.balance;
        changeVirtualCurrency(state.virtual_currency_amount + "");
      } else {
        state.currency_amount = state.balance;
        changeCurrency(state.currency_amount + "");
      }
    };
    // 点击确认
    const submitForm = () => {
      if (!state.currency_name) {
        // 未选择币种
        return;
      }
      if (!state.virtualCoin) {
        // 请选择币种
        ElMessage.error("请选择数字货币币种");
        return;
      }

      if (state.exchange_type) {
        if (!state.virtual_currency_amount) {
          // 请输入数字货币金额
          ElMessage.error(t("stock.digitalTip"));
          return;
        }
        if (!state.currency_amount) {
          // 请输入法币金额
          ElMessage.error(t("stock.fiatTip"));
          return;
        }
        if (state.virtual_currency_amount > state.balance) {
          // 余额不足
          ElMessage.error(t("lever.balanceinsu"));
          return;
        }
        if (Number(state.virtual_currency_amount) <= 0) {
          return;
        }
        if (
          state.virtual_currency_amount >
          state.defaultFiat?.max_exchange_virtual_num
        ) {
          ElMessage.error(
            t("stock.maximumLimit") +
              state.defaultFiat?.max_exchange_virtual_num
          );
          return;
        }
        if (
          state.virtual_currency_amount <
          state.defaultFiat?.min_exchange_virtual_num
        ) {
          ElMessage.error(
            t("stock.minimumLimit") +
              state.defaultFiat?.min_exchange_virtual_num
          );
          return;
        }
      } else {
        if (!state.currency_amount) {
          // 请输入法币金额
          ElMessage.error(t("stock.fiatTip"));
          return;
        }
        if (!state.virtual_currency_amount) {
          // 请输入数字货币金额
          ElMessage.error(t("stock.digitalTip"));
          return;
        }

        if (state.currency_amount > state.balance) {
          // 余额不足
          ElMessage.error(t("lever.balanceinsu"));
          return;
        }
        if (Number(state.currency_amount) <= 0) {
          return;
        }
        if (state.currency_amount > state.defaultFiat?.max_exchange_num) {
          ElMessage.error(
            t("stock.redemptionMaxLimit") + state.defaultFiat?.max_exchange_num
          );
          return;
        }
        if (state.currency_amount < state.defaultFiat?.min_exchange_num) {
          ElMessage.error(
            t("stock.redemptionMinLimit") + state.defaultFiat?.min_exchange_num
          );
          return;
        }
      }
      let param = {
        id: state.defaultFiat?.id,
        exchange_amount: state.exchange_type
          ? state.virtual_currency_amount
          : state.currency_amount,
        exchange_type: state.exchange_type ? 1 : 2,
      };
      state.loading = true;
      stockCurrencyExchange(param)
        .then((res) => {
          if (res.code === 200) {
            ElMessage({
              type: "success",
              message: res.message,
            });
            getBalance();
            state.currency_amount = "";
            state.virtual_currency_amount = "";
            state.loading = false;
            emit("getbalance");
          }
        })
        .catch(() => {
          state.loading = false;
        });
    };
    return {
      state,
      changeType,
      getcurrency,
      getBalance,
      allin,
      submitForm,
      changeVirtualCurrency,
      changeCurrency,
      systemInfo,
      changePrice,
      rideFix,
      exceptFix,
      init,
      updateVirtualArr,
      decimalDigitsInputFilter,
    };
  },
};
</script>

<style scoped lang="less">
.acount-exchange {
  padding: 4px 20px;
  box-sizing: border-box;
  /deep/.el-input {
    line-height: 52px;
  }
  /deep/.el-input__inner {
    height: 52px;
  }
}
.transfer {
  width: 100%;
  height: 120px;
  padding: 0 10px 0 7px;
  box-sizing: border-box;
}
.left {
  width: 13px;
  height: 54px;
}
.round {
  width: 6px;
  height: 6px;
  border-radius: 50%;
}
.small-round {
  width: 4px;
  height: 4px;
  border-radius: 50%;
}
.bg-2E {
  background: @blue;
}
.bg-CF {
  background: #cf2f43;
}
.bg-EA {
  background: #eaecef;
}
.hua-center {
  width: 250px;
  height: 100%;
}
.h-c-half {
  height: 50%;
  width: 100%;
  // line-height: 60px;
}
.mr-17 {
  margin-inline-end: 17px;
}
.ml-17 {
  margin-inline-start: 17px;
}
.hua-right {
  height: 100px;
  width: 60px;
  img {
    width: 19.9px;
    height: 19.9px;
  }
}
.el-input__inner {
  border: 1px solid white;
}
.mb-20 {
  margin-bottom: 20px;
}
.mb-30 {
  margin-bottom: 30px;
}
.mb-10 {
  margin-bottom: 10px;
}
.el-select {
  width: 100%;
}
.el-input-number {
  width: 100%;
}
.balance {
  width: 100%;
}
.btn {
  height: 46px;
  line-height: 46px;
}
.w30 {
  width: 30px;
}
.huazhuan-center > .el-input__inner {
  text-align: center !important;
}
.rate-box {
  padding: 16px;
  // background: #f8f8f8;
  border-radius: 26px;
  width: 100%;
}
.mb-6 {
  margin-bottom: 6px;
}
.mb-20 {
  margin-bottom: 20px;
}
.mb-30 {
  margin-bottom: 30px;
}
.mb-32 {
  margin-bottom: 32px;
}
.ml-16 {
  margin-inline-start: 16px;
}
.w-150 {
  width: 150px;
}
.flex-grow-1 /deep/input {
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
  width: 100%;
  box-sizing: border-box;
}
.top /deep/ input {
  padding-inline-end: 45px;
}
</style>
